package com.xsz.service;

import com.xsz.entity.RoleUserKey;
import com.xsz.entity.User;
import com.xsz.mapper.UserMapper;
import com.xsz.util.KeyUtil;
import com.xsz.util.MD5Utils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserService {
	@Resource
	UserMapper userMapper;

	@Resource
	RoleUserService roleUserService;

	//新建
	public User add(User user) {

		user.setId(KeyUtil.getId());
		if(userMapper.insert(user)>0){
			RoleUserKey record= new RoleUserKey();
			record.setUid(user.getId());
			record.setRoleId("2");
			roleUserService.insert(record);
			return  user;
		}else{
			return null;
		}


	}

	//修改

	public int update(User user) {
		return userMapper.updateByPrimaryKeySelective(user);
	}


	//删除

	public void delete(String id) {
		userMapper.deleteByPrimaryKey(id);
	}

	//查询

	public User selectById(String id) {
		return userMapper.selectByPrimaryKey(id);
	}


	public List<User> getAll() {
		return userMapper.selectAll();
	}


	public User login(String name,String pwd) {
		User user1=new User();
		user1.setPwd(pwd);
		user1.setName(name);
		User user=userMapper.selectLogin(user1);

		return user;
	}

	public List<User> likeName(String name) {
		return userMapper.selectByLikeName(name+"%");
	}

	public User getByName(String name) {
		return userMapper.selectByName(name);
	}

	public User selectByIdAndPwd(User user) {
		String password = MD5Utils.encrypt(user.getName(), user.getPwd());
		user.setPwd(password);
		User user1=new User();
		user1.setPwd(password);
		user1.setId(user.getId());
		return userMapper.selectByIdAndPwd(user1);
	}

	public int updatePwdById(User user) {
		String password = MD5Utils.encrypt(user.getName(), user.getPwd());
		user.setPwd(password);
		User user1=new User();
		user1.setPwd(password);
		user1.setId(user.getId());
		return userMapper.updateByPrimaryKeySelective(user1);
	}

}
